package br.ufpb.di.ppgi.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CPFFlexFormatter {
	private static final Pattern REGEX = Pattern.compile("(\\d{0,3})[.]?(\\d{3})[.]?(\\d{3})-?(\\d{2})");
    private static final String FORMATED_BLANK = "000.000.000-00";
    private static final String FORMATED_GROUP = "$1.$2.$3-$4";
    private static final String UNFORMATED_BLANK = "00000000000";
    private static final String UNFORMATED_GROUP = "$1$2$3$4";
	
    public CPFFlexFormatter() {}
    
    private String formatFillZero(String value) {
    	return FORMATED_BLANK.substring(0, 14-value.length()) + value;
    }
    
    private String unformatFillZero(String value) {
    	return UNFORMATED_BLANK.substring(0, 11-value.length()) + value;
    }
    
    public String format(String value) {
    	return value == null ? null : formatFillZero(matchAndReplace(value,FORMATED_GROUP));
    }
    
    public String unformat(String value) {
    	return value == null ? null : unformatFillZero(matchAndReplace(value,UNFORMATED_GROUP));
    }
    
    private String matchAndReplace(String value,String replacement) {
    	Matcher matcher = REGEX.matcher(value);
        String result = null;
        if (matcher.matches()) {
            result = matcher.replaceAll(replacement);
        } else {
            throw new IllegalArgumentException("Value is not properly formatted.");
        }
        return result;
    }
	
    public static void main(String[] args) {
    	System.out.println(new CPFFlexFormatter().unformat(null));
    	System.out.println(new CPFFlexFormatter().format("339.254-09"));
		System.out.println(new CPFFlexFormatter().unformat("339.254-09"));
	}
}
